<template>
  <n-popover :disabled="!popMsg" :placement="placement">
    <template #trigger>
      <n-button quaternary class="h-24 w-24 text-gray-500 f-c-c ml-5" @click="copyText">
        <template #icon>
          <n-icon size="size">
            <icon-custom-copyIcon />
          </n-icon>
        </template>
      </n-button>
    </template>
    <template #default>{{ popMsg }}</template>
  </n-popover>
</template>

<script setup>
const props = defineProps({
  text: {
    type: String,
    default: '',
  },
  size: {
    type: Number,
    default: 18,
  },
  popMsg: {
    type: String,
    default: '',
  },
  placement: {
    type: String,
    default: 'top',
  },
})

const copyText = async () => {
  // try {
  //   navigator.clipboard.writeText(props.text)
  //   $message.success('复制成功')
  // } catch (err) {
  //   $message.error('复制失败')
  // }
  if (navigator.clipboard && window.isSecureContext) {
    await navigator.clipboard.writeText(props.text)
    $message.success('复制成功')
  } else {
    // 使用“超出视口隐藏文本区域”方法来实现旧的剪切板操作
    const textArea = document.createElement('textarea')
    textArea.value = props.text

    // 移动文本区域到视口之外
    textArea.style.position = 'absolute'
    textArea.style.left = '-999999px'

    document.body.prepend(textArea)
    textArea.select()

    try {
      document.execCommand('copy')
      $message.success('复制成功')
    } catch (error) {
      console.error(error)
      $message.error('复制失败')
    } finally {
      textArea.remove()
    }
  }
}
</script>
